package com.fj.netty.rpc.server.handler;

import com.fj.netty.rpc.message.RpcRequestMessage;
import com.fj.netty.rpc.message.RpcResponseMessage;
import com.fj.netty.rpc.server.service.ServiceFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
@Slf4j
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage rpcRequestMessage) throws Exception {
        RpcResponseMessage responseMessage = new RpcResponseMessage();
        responseMessage.setSequenceId(rpcRequestMessage.getSequenceId());
        try{
            String interfaceName = rpcRequestMessage.getInterfaceName();
            Class<?> service = ServiceFactory.getService(interfaceName);
            Object instance = service.newInstance();
            Method method = service.getMethod(rpcRequestMessage.getMethodName(), rpcRequestMessage.getParamTypes());
            Object result = method.invoke(instance, rpcRequestMessage.getParamObjects());
            responseMessage.setReturnValue(result);
        }catch (Exception e){
            responseMessage.setExceptionValue(e);
        }
        ctx.writeAndFlush(responseMessage);
    }
}
